import React, { useEffect, useState } from 'react'
import { TreeSelect, Modal, Button, message } from "antd"
import { get } from '../../util/get';
import { put } from "../../util/put"
import PubSub from 'pubsub-js';
import style from './index.module.css'
export default function LinkModal(props) {
    const { SHOW_PARENT } = TreeSelect;
    const { v, setV } = props
    const [allValue, setAllValue] = useState([]);
    const [value, setValue] = useState([])
    const [id, setId] = useState('')
    const token = localStorage.getItem('TOKEN')
    const toTreeData =(data)=>{
        return data.map(i => {
            return {
                title: `${i.description}:${i.method} - ${i.uri}`,
                value: Number(i.id?i.id:i.permissionId),
                key: Number(i.id?i.id:i.permissionId)
            }
        })
    }
    useEffect(() => {
        PubSub.subscribe('linkrole', (_, data) => {
            setId(data.id)
            setValue(toTreeData(data.permissionVoList))
        })
    }, [])
    useEffect(() => {
        if (v) {
            get('/user/permission/allList?key=', token).then(res => {
                const { data, code, msg } = res.data
                if (!code) {
                    setAllValue(toTreeData(data))
                }
                else message.error(msg)
            })
        }
    }, [v, token])
    const onChange = (newValue) => {
        console.log('onChange ', newValue);
        setValue(newValue);
    };
    const tProps = {
        treeData: allValue,  //总
        value,  //有
        onChange,
        treeCheckable: true,
        showCheckedStrategy: SHOW_PARENT,
        placeholder: 'Please select',
        style: {
            width: '100%',
        },
    };
    const handleEditCancel = () => {
        setV(false)
    }
    const handleLink = async () => {
        // console.log(value, id,'handleLink')
        let res= null;
        if(value.length>0&&value[0] instanceof Object){
           const arr = value.map(i=>i.value)
           res = await put(`/user/role/${id}/relate`, { permissionIdList: arr }, token)
        }
        else{
             res = await put(`/user/role/${id}/relate`, { permissionIdList: value }, token)
        }
        const { code, msg } = res.data
        if(!code)   {
            message.success(msg)
            setV(false)
        }
        else message.error(msg)
    }
    return (
        <Modal title="编辑角色资源" className={style.modal} visible={v} footer={null} onCancel={handleEditCancel}>
            <TreeSelect {...tProps} />
            <Button type="primary" onClick={handleLink} htmlType="submit">
                关联资源
            </Button>
        </Modal>
    )
}
